package com.jiyi.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.jiyi.bean.zone.ZoneHaoYouBean;
import com.jiyi.event.UserInfoEvent;
import com.swift.base.ActivityBase;
import com.swift.base.ApplicationBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/*
 *
 * 完善资料
 * */

public class PerfectInformation extends ActivityBase{

	private TextView mSave;
	private EditText mCompanyName;
	private EditText mAddress;
	private EditText mTelephone;
	private EditText mEmail;
	private EditText mBirthday;
	private EditText mIntroduction;
	private EditText mUsername;

	private String companyName;
	private String address;
	private String phone;
	private String email;
	private int type;
	private String birthday;
	private RadioButton mMale;
	private RadioButton mFemale;
	private String userName;
	private ImageView mBack;
	private String userId;
	private String companyId;
	private RadioGroup mRadioGroup;
	private String info;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_information);
		initView();
		initData();
		initEvent();

	}

	private void initEvent() {
		mBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		mSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (TextUtils.isEmpty(mUsername.getText().toString()))
				{
					ToastUtil.getInstances().showMsg("请填写昵称");
					return;
				}
				final String nickName = mUsername.getText().toString();

				String url = AppConfig.TEXT_HOST+"/Api/User/save";
				RequestQueue requestQueue = Volley.newRequestQueue(PerfectInformation.this);
				StringRequest stringRequest = new StringRequest(
						Request.Method.POST, url,
						new Listener<String>() {
							@Override
							public void onResponse(String response) {
								Toast.makeText(PerfectInformation.this, "保存成功", 0).show();
								UserInfoUtil.setCurrentUserName(nickName);
								ZoneHaoYouBean mTemp = new ZoneHaoYouBean();
								mTemp.setName(nickName);
								EventBus.getDefault().post(new UserInfoEvent(mTemp));
							}
						}, new ErrorListener() {
							@Override
							public void onErrorResponse(VolleyError error) {
								Toast.makeText(PerfectInformation.this, "保存失败", 0).show();
							}
						}) {
					@Override
					protected Map<String, String> getParams() {
						// 在这里设置需要post的参数
						Map<String, String> map = new HashMap<String, String>();
						map.put("keyword", mCompanyName.getText().toString().trim());
						map.put("ID", userId);
						map.put("id", companyId);
						map.put("email", mEmail.getText().toString().trim());
						map.put("tel", mTelephone.getText().toString().trim());
						map.put("addr", mAddress.getText().toString().trim());
						map.put("birth", mBirthday.getText().toString().trim());
						map.put("male", type+"");
						map.put("textarea", mIntroduction.getText().toString().trim());
						map.put("access_token", UserInfoUtil.getCurrentUserAccessToken());
						map.put("name", nickName);

						return map;
					}
				};
				requestQueue.add(stringRequest);
			}
		});

		mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				if(arg1 == mMale.getId()){
					type = 0;
				}else if(arg1 == mFemale.getId()){
					type = 1;
				}
				
			}
		});		
	}

	private void initData() {

		int userId = ApplicationBase.LocalData.getInt("user_id", 0);
		String url = AppConfig.TEXT_HOST+"/Api/User/getUserInfo/"+AppConfig.ACCESS_TOKEN+"/"+ UserInfoUtil.getCurrentUserAccessToken()
				+"/userId/"+ userId;
		RequestQueue queue = Volley.newRequestQueue(this);
		StringRequest request = new StringRequest(Request.Method.GET, url,
				new Listener<String>() {

					@Override
					public void onResponse(String response) {
						parseJSON(response);

					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {

					}
				});

		queue.add(request);
	}

	protected void parseJSON(String str) {
		String string = str.replace("ï»¿", "");
		hasJsonData(string);
		try {
			JSONObject obj = new JSONObject(string);
			JSONObject jsonObject = obj.getJSONObject("data");

			userId = jsonObject.getString("userid");
			userName = jsonObject.getString("username");
			companyName = jsonObject.getString("companyname");
			companyId = jsonObject.getString("companyid");
			address = jsonObject.getString("address");
			phone = jsonObject.getString("mobile");
			email = jsonObject.getString("email");
			type = jsonObject.getInt("sex");
			info = jsonObject.getString("info");
			int lo = jsonObject.getInt("birthday");
			Date currentTime = new Date(lo);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			birthday = formatter.format(currentTime);

		} catch (JSONException e) {
			e.printStackTrace();
		}

		mUsername.setText(userName);
		mAddress.setText(address);
		mCompanyName.setText(companyName);
		mTelephone.setText(phone);
		mEmail.setText(email);
		mBirthday.setText(birthday);
		mIntroduction.setText(info);

		if (type == 0) {
			mMale.setChecked(true);
		} else {
			mFemale.setChecked(true);
		}
	}

	private void initView() {

		mUsername = (EditText) findViewById(R.id.et_username);
		mBack = (ImageView) findViewById(R.id.iv_toolbar_back);
		mSave = (TextView) findViewById(R.id.tv_save);
		mCompanyName = (EditText) findViewById(R.id.et_companyName);
		mAddress = (EditText) findViewById(R.id.et_address);
		mTelephone = (EditText) findViewById(R.id.et_telephone);
		mEmail = (EditText) findViewById(R.id.et_email);
		mBirthday = (EditText) findViewById(R.id.et_birthday);
		mIntroduction = (EditText) findViewById(R.id.et_introduction);
		mRadioGroup = (RadioGroup) findViewById(R.id.rl_radiogroup);

		mMale = (RadioButton) findViewById(R.id.bt_male);
		mFemale = (RadioButton) findViewById(R.id.bt_female);

	}

	protected boolean hasJsonData(String json) {
		return !(json.equalsIgnoreCase("null") || json.equalsIgnoreCase("[]") || json
				.equalsIgnoreCase("{}"));
	}

}
